from flask import make_response, jsonify, request
from apps.api import api
from apps.gm.globalmanger import GlobalManager
from apps.utils.getinterfaceipinfo import GetInterFaceIpInfo


@api.route('/v1.0/opertest/', methods=['GET', 'POST'])
def opertest():
    """
     上面 /v1.0/test/ 定义的url最后带上"/"：
     1、如果接收到的请求url没有带"/"，则会自动补上，同时响应视图函数
     2、如果/v1.0/test/这条路由的结尾没有带"/"，则接收到的请求里也不能以"/"结尾，否则无法响应
    """
    # 获取参数
    #if request.method == "POST":
    		 # 获取表单参数
    #    username = request.form.get("username")
    #    password = request.form.get("password")
    		 # 获取json参数
    #    data = request.get_json()
    #else:
    		 #获取get参数
    #    username = request.args.get("username")
    #    password = request.args.get("password")
    data = {'username': 'xxx', 'password': 'xxxx'}
    response = jsonify(code=200,
                       msg="success",
                       data=data)
    return response
    # 也可以使用 make_response 生成指定状态码的响应
    # return make_response(response, 200)

# http://127.0.0.1/api/v1.0/add/192.9.9.11/enps50/172.3.6.9/255.255.255.0/172.3.6.1
@api.route('/v1.0/addipgw/<hip>/<nc>/<aip>/<mask>/<gw>/', methods=['GET', 'POST'])
def addipgw(hip, nc, aip, mask, gw):
    print("添加的信息如下：", hip, nc, aip, mask, gw)
    response = jsonify(code=200,
                       msg="success",
                       data=[hip, nc, aip, mask, gw])
    return response

@api.route('/v1.0/addipnogw/<hip>/<nc>/<aip>/<mask>/<gw>/', methods=['GET', 'POST'])
def addipnogw(hip, nc, aip, mask, gw):
    print("添加的信息如下：", hip, nc, aip, mask, gw)
    response = jsonify(code=200,
                       msg="success",
                       data=[hip, nc, aip, mask, gw])
    return response

# http://127.0.0.1:5000/api/v1.0/addip?ip=192.168.1.223&nc=enp5s0&aip=172.36.36.2&mk=255.255.255.0
@api.route('/v1.0/addip/', methods=['GET', 'POST'])
def addip():
    requests = request.args
    print("添加的IP信息：", requests)
    hip = requests.get("ip")
    nc = requests.get("nc")
    aip = requests.get("aip")
    mk = requests.get("mk")
    gw = requests.get("gw")

    gm = GlobalManager()
    if nc not in gm.device_uuid[hip]:
        response = jsonify(code=500,
                           msg="error",
                           data="uuid 不存在")
        return response

    uuid = gm.device_uuid[hip][nc]
    print("uuid = ", uuid)
    if gw == None:
        cmd = "nmcli con mod " + uuid + " " + "+ipv4.addresses " + aip + "/" + str(exchange_mask(mk))
    else:
        cmd = "nmcli con mod " + uuid + " " + "+ipv4.addresses " + aip + "/" + str(exchange_mask(mk)) + " +ipv4.gateway " + gw
    print("add ip cmd = ", cmd)

    host_info = gm.get_dic_from_type(1)[hip]
    gifi = GetInterFaceIpInfo(host_info[0], host_info[1], host_info[2], host_info[3])
    ret = gifi.exec_cmd(cmd)
    if ret is None:
        response = jsonify(code=500,
                           msg="error",
                           data="执行nmcli con mod 失败")
        return response

    if ret.get('status') != 0:
        response = jsonify(code=500,
                           msg="error",
                           data="添加IP失败，请重新添加！！！")
        return response

    cmd = "nmcli dev connect " + nc
    ret = gifi.exec_cmd(cmd)
    if ret is None:
        response = jsonify(code=500,
                           msg="error",
                           data="执行激活IP命令建立ssh连接失败！！！")
        return response

    if ret.get('status') != 0:
        response = jsonify(code=500,
                           msg="error",
                           data="添加IP激活失败，请重新添加！！！")
        return response

    response = jsonify(code=200,
                       msg="success",
                       data="add sucess")
    return response

# http://127.0.0.1:5000/api/v1.0/delip?ip=192.168.1.223&nc=enp5s0&aip=172.36.36.2&mk=255.255.255.0
@api.route('/v1.0/delip/', methods=['GET', 'POST'])
def delip():
    requests = request.args
    print("添加的IP信息：", requests)
    hip = requests.get("ip")
    nc = requests.get("nc")
    aip = requests.get("aip")
    mk = requests.get("mk")
    gw = requests.get("gw")

    gm = GlobalManager()

    if aip in gm.manager_ip:
        response = jsonify(code=500,
                           msg="error",
                           data="管理ip 不可删除")
        return response

    if nc not in gm.device_uuid[hip]:
        response = jsonify(code=500,
                           msg="error",
                           data="uuid 不存在")
        return response

    uuid = gm.device_uuid[hip][nc]
    print("uuid = ", uuid)
    cmd = "nmcli con mod " + uuid + " " + "-ipv4.addresses " + aip + "/" + str(
        exchange_mask(mk))

    host_info = gm.get_dic_from_type(1)[hip]
    gifi = GetInterFaceIpInfo(host_info[0], host_info[1], host_info[2], host_info[3])
    ret = gifi.exec_cmd(cmd)
    if ret is None:
        response = jsonify(code=500,
                           msg="error",
                           data="执行删除IP建立ssh连接失败！！！")
        return response

    if ret.get('status') != 0:
        response = jsonify(code=500,
                           msg="error",
                           data="删除IP失败！！！")
        return response

    cmd = "nmcli dev connect " + nc
    ret = gifi.exec_cmd(cmd)
    if ret is None:
        response = jsonify(code=500,
                           msg="error",
                           data="执行激活IP命令建立ssh连接失败！！！")
        return response

    if ret.get('status') != 0:
        response = jsonify(code=500,
                           msg="error",
                           data="删除IP激活失败，请重新添加！！！")
        return response

    response = jsonify(code=200,
                       msg="success",
                       data="del sucess")
    return response


# 255.255.255.0 -> 24
def exchange_mask(mask):
    if mask == None or len(mask) == 0:
        return ""
    # 计算二进制字符串中 ‘1‘ 的个数
    count_bit = lambda bin_str: len([i for i in bin_str if i == "1"])
    # 分割字符串格式的子网掩码为四段列表
    mask_splited = mask.split(".")
    # 转换各段子网掩码为二进制, 计算十进制
    mask_count = [count_bit(bin(int(i))) for i in mask_splited]
    return sum(mask_count)